//
//  SSSRecordOrderToPayViewController.m
//  SSSMerchant
//
//  Created by 谢曦 on 2017/3/22.
//  Copyright © 2017年 xnxin. All rights reserved.
//

#import "SSSRecordOrderToPayViewController.h"
#import "SSSRecordOrderToPayCell.h"
#import "SSSAlertWindow.h"
#import "SSSRecordOrderToPayAlertWindowCustomView.h"
#import "SSSRecordOrderToDownlinePayViewController.h"
@interface SSSRecordOrderToPayViewController ()
{
    CGFloat _limitMoney;//限制金额
      CGFloat _totalMoney;//总金额
}
@property (weak, nonatomic) IBOutlet UILabel *allSelectedButton;
@property (weak, nonatomic) IBOutlet UILabel *totalLable;
@property (weak, nonatomic) IBOutlet UILabel *limitLable;
@property (nonatomic,strong) UIView *orderToPayBottomBar;
    @property (nonatomic,strong) NSMutableArray <SSSRecordOrderModel *> *selectedArr;
@end

@implementation SSSRecordOrderToPayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    self.title=@"待支付";
    [self.tableView registerNib:[UINib nibWithNibName:@"SSSRecordOrderToPayCell" bundle:nil
                                 ] forCellReuseIdentifier:@"SSSRecordOrderToPayCell"];
   
    self.isShowBottomBar=NO;
    [self orderToPayBottomBar];
    [self configData];
    [self addObserver:self forKeyPath:@"selectedArr" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];

   }
-(void)configData{
    _selectedArr=@[].mutableCopy;
    NSMutableArray *arr=@[].mutableCopy;
    for (int i=0; i<10; i++) {
        SSSRecordOrderModel *model=[SSSRecordOrderModel new];
        model.money=[NSString stringWithFormat:@"1000%.2f",arc4random()%20*1.0];
       
        model.date=@"2017-3-20";
        model.time=@"13:20:09";
        model.phone=@"13320990999";
        model.type=arc4random()%2+1;
        model.customerNumber=@"e7qwtye7ywqewqey";
        model.uploadMoney=@"1700888";
        model.name=@"小明的店";
        model.customerNickname=@"小明没看那个命名";
        model.orderNumber=@"126537621536213567125763";
        model.personName=@"小明";
        [arr addObject:model];
    }
   

    self.dataArr=arr.copy;
    [self.tableView reloadData];
    
    

}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    NSLog(@"%@---%@",object,change);
   
    if(  [change[@"kind"] intValue]==NSKeyValueChangeInsertion){
    //插入数据
        SSSRecordOrderModel *model= [change[@"new"] firstObject];
        _totalMoney+=[model.money floatValue ];
        model.selected=YES;
        
    }
    if(  [change[@"kind"] intValue]==NSKeyValueChangeRemoval){
        //移除数据
        SSSRecordOrderModel *model= [change[@"old"] firstObject];
        _totalMoney-=[model.money floatValue ];
      
    }
 
//    for (int i=0; i<self.selectedArr.count; i++) {
//        SSSRecordOrderModel *model=self.selectedArr[i];
//        totalPay+=[model.money floatValue];
//           }
//
    NSString *total=[NSString stringWithFormat:@"合计:¥%.2f",_totalMoney];
    _totalLable.attributedText=[self attributeStrWithStr:total];

   
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SSSRecordOrderToPayCell *cell=[tableView dequeueReusableCellWithIdentifier:@"SSSRecordOrderToPayCell" forIndexPath:indexPath];
  SSSRecordOrderModel *model= self.dataArr[indexPath.row];
     cell.model=model;
     __weak typeof(cell)wCell= cell;
    wCell.SSSRecordOrderToPayCellSelectBlock=^(UIButton *button){
        
        if ( button.selected==NO) {
//           当使用kvo观察数组变化时候  不能直接调用[self.selectedArr addObject:model] 这样kvo方法不会调用
            [[self mutableArrayValueForKey:@"selectedArr"] addObject:model];
        }
        if (button.selected==YES) {
             [[self mutableArrayValueForKey:@"selectedArr"] removeObject:model];
           
        }
        model.selected=!button.selected;
        cell.model=model;

    };
   
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 93;
}
#pragma mark - action
- (IBAction)surePay:(id)sender {
    if(_totalMoney>_limitMoney){
    //超过限额
        NSAttributedString *str1=[[NSAttributedString alloc] initWithString:@"支付失败" attributes:@{NSFontAttributeName:Font(18),NSForegroundColorAttributeName: [UIColor colorWithHex:@"6D6D6D"]}];
        ;
        NSAttributedString *str2=[[NSAttributedString alloc] initWithString:@"金额超出每日限额啦~" attributes:@{NSFontAttributeName:Font(13),NSForegroundColorAttributeName: [UIColor colorWithHex:@"BBBBBB"]}];
        ;
        
        SSSAlertWindow *alert=[SSSAlertWindow alertWindowWithPicName:@"img_payfail" contentTextArr:@[str1,str2] themeButtontText:@"确认" cancleButtonText:@""];
        [alert show];

    }
    
    else{
     SSSAlertWindow *alert=   [self customAlertWindow];
    [alert show];
    }
    
    
}
    
- (IBAction)allSelected:(UIButton *)allSelectedButton {
    allSelectedButton.selected=!allSelectedButton.selected;
    if (allSelectedButton.selected==YES) {
        //全选
        [self.selectedArr removeAllObjects];
        //调用kvo方法 数组个数次
        [[self mutableArrayValueForKey:@"selectedArr"] addObjectsFromArray:self.dataArr];
     

    }
    else{
        [[self mutableArrayValueForKey:@"selectedArr"] removeAllObjects];
       
           }
     [self.tableView reloadData];
   
}

#pragma mark - private
 //线上
-(void)toOnlinePay{

}
 //线下
-(void)toDownlinePay{
    SSSRecordOrderToDownlinePayViewController *downlinevc=[[SSSRecordOrderToDownlinePayViewController alloc] init];
    downlinevc.model=self.dataArr[0];
    downlinevc.totalPayMoney=_totalMoney;
    [self.navigationController pushViewController:downlinevc animated:YES];
}
  #pragma mark - setter
-(UIView *)orderToPayBottomBar{
    if (!_orderToPayBottomBar) {
        _orderToPayBottomBar=[[[NSBundle mainBundle] loadNibNamed:@"SSSRecordOrderToPayBottomBar" owner:self options:nil]lastObject];
        
        [self.view addSubview:_orderToPayBottomBar ];
        [_orderToPayBottomBar mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.height.mas_equalTo(60);
        }];
        self.tableView.height-=60;
        _limitMoney=50000.00;
        _limitLable.text=[NSString stringWithFormat:@"每日限额： %.2f",_limitMoney];
        NSString *total=[NSString stringWithFormat:@"合计:¥0.00"];
        _totalLable.attributedText=[self attributeStrWithStr:total];
    }
    return _orderToPayBottomBar;

}
-(NSMutableAttributedString *)attributeStrWithStr:(NSString *)str{

       
        NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:str];
        
        [attStr addAttribute:NSFontAttributeName value:Font(15) range:NSMakeRange(0,3)];
        [attStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHex:@"6D6D6D"] range:NSMakeRange(0,3)];
        
        [attStr addAttribute:NSFontAttributeName value:Font(18) range:NSMakeRange(3, str.length-3)];
        [attStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHex:@"FF6E35"] range:NSMakeRange(3, str.length-3)];

    return attStr;
}
-(SSSAlertWindow *)customAlertWindow{
    
    
    SSSRecordOrderToPayAlertWindowCustomView *customView=[[[NSBundle mainBundle] loadNibNamed:@"SSSRecordOrderToPayAlertWindowCustomView" owner:self options:nil]lastObject];
    customView.bounds=CGRectMake(0, 0, SCREEN_WIDTH-30, 180);
    SSSAlertWindowButton *sure=[SSSAlertWindowButton buttonWithTitle:@"确认" highLight:YES];
    SSSAlertWindow *alert=[SSSAlertWindow picAndTextAlertViewWithPicName:@"img_pay" customCenterView:customView buttonArr:@[sure]];
    //    __weak typeof(customView) wCustomView = customView;
    __weak typeof(alert) walert = alert;
    walert.SSSAlertWindowButtonClick=^(NSInteger index){
       
        [walert dismiss];
        if (customView.payType==0) {
            [self toOnlinePay];
        }
        if (customView.payType==1) {
            [self toDownlinePay];
        }
        
    };
    return alert;
    
}

-(void)dealloc{
    [self removeObserver:self forKeyPath:@"selectedArr"];
}
@end
